#include "xxx_mapping.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

/*
 * Return an unused xxx_mapping_item.
 *  @info: pointer to a loaded xxx_info
 *  return:
 *      On success, return a pointer to xxx_mapping_item.
 *      On error, return NULL.
 */
struct xxx_mapping_item* new_mapping(struct xxx_info *info)
{
    for (int i = 0; i < info->mapping_item_count; i++)
    {
        if (info->mapping_items[i].is_used == false)
        {
            info->mapping_items[i].is_used = true;
            return info->mapping_items + i;
        }
        else if (info->mapping_items[i].shown_ino_t == 0)
        {
            // invalid, treate it as not used
            return info->mapping_items + i;
        }
    }
    return NULL; // no room for mapping
}

/*
 * Find a xxx_mapping_item with a specific inode number.
 *  @info: pointer to a loaded xxx_info
 *  @shown_ino_t: inode number
 *  return:
 *      On success, return a pointer to xxx_mapping_item.
 *      On error, return NULL.
 */
struct xxx_mapping_item* find_mapping(const struct xxx_info *info, const ext2_ino_t shown_ino_t)
{
    for (int i = 0; i < info->mapping_item_count; i++)
    {
        if (info->mapping_items[i].is_used == true && info->mapping_items[i].shown_ino_t == shown_ino_t)
        {
            return info->mapping_items + i;
        }
    }
    return NULL;
}

/*
 * Mark this xxx_mapping_item as unused.
 */
inline void delete_mapping(struct xxx_mapping_item* item)
{
    item->is_used = false;
}
